import React, { Component, ComponentClass } from 'react';
import Taro from '@tarojs/taro';
import {View, Block, Picker, Text} from '@tarojs/components'
import {vcmonitor} from "../../../utils/tools";
import {
  IDENTITY,
  INVOICE_PAGE,
  SUPPLIER_PERFORMANCE,
  TARO_ENV
} from '../../../constants/api'
import {http} from "../../../utils/http";
import GzhAuth from "../../../components/gzh-auth/gzh-auth"
import Water from "../../components/water-mark/index";
import {user} from "../../../utils/user.service";
import {UserIdentity} from "../../../utils/server.interface";
import {newHttp} from "../../../utils/request";
import './index.scss'

type PageOwnProps = {};
type PageState = {
  loadMoreStatus: 'more' | 'noMore' | 'loading'
  listData: any
  queryData: any
  supplierIndex: number
  supplierChecked: string
  supplierList: any
}

class Index extends Component {
  state: PageState = {
    loadMoreStatus: 'loading',
    supplierChecked: '',
    supplierIndex: 0,
    supplierList: [],
    listData: [],
    queryData: {
      search_add_date_start: '',
      search_add_date_end: '',
      search_supplier_id: '',
      page: 1,
      pageSize: 10,
    }
  }
  page = 1
  async componentDidShow() {
    this.page = 1
    vcmonitor(this)
    const isLogin = await user.checkLogin()
    if (!isLogin) {
      Taro.showToast({
        title: '你还未登录，请登录',
        icon: 'none',
      })
      const timer = setTimeout(() => {
        clearTimeout(timer)
        Taro.switchTab({url: '/pages/index/index'})
      }, 1500)
      return
    } else {
      const userIdentity: any = await http.get<UserIdentity>(IDENTITY, {})
      if (userIdentity && userIdentity.isSupplier) {
        let supplierChecked = ''
        let supplierIndex = Taro.getStorageSync('mySupplierIndex') || 0
        if (userIdentity.SupplierList.length > 0) {
          supplierIndex = userIdentity.SupplierList.length < supplierIndex ? userIdentity.SupplierList.length - 1 : supplierIndex
          supplierChecked = userIdentity.SupplierList[supplierIndex].company
          this.state.queryData.search_supplier_id = userIdentity.SupplierList[supplierIndex].supplier_id
          Taro.setStorageSync('mySupplierIndex', supplierIndex)
        }
        this.setState({supplierList: userIdentity.SupplierList, supplierChecked, supplierIndex})
      } else {
        Taro.showToast({
          title: '您还没有供应商，请确认用户身份',
          icon: 'none',
          mask: true
        })
        const timer = setTimeout(() => {
          clearTimeout(timer)
          Taro.switchTab({url: '/pages/index/index'})
        }, 1500)
        return
      }
    }
    await this.getListData(this.state.queryData)
  }

  async onReachBottom() {
    if (this.state.loadMoreStatus != 'noMore') {
      this.setState({loadMoreStatus: 'loading'})
      const {queryData} = this.state
      this.page++
      queryData['page'] = this.page
      const old = this.state.listData
      const data = await newHttp.get(INVOICE_PAGE, queryData)
      if (data.data.length < queryData.length) {
        this.setState({loadMoreStatus: 'noMore'})
      } else {
        this.setState({loadMoreStatus: 'more'})
      }
      this.setState({queryData, listData: [...old, ...data.data]})
    }
  }

  async getListData(queryData) {
    Taro.showLoading({title: '加载中'})
    const data = await newHttp.get(SUPPLIER_PERFORMANCE, queryData)
    if (JSON.stringify(data) !== '{}'){
      if (data.data.length < queryData.length) {
        this.setState({loadMoreStatus: 'noMore'})
      } else {
        this.setState({loadMoreStatus: 'more'})
      }
      this.setState({queryData, listData: data.data})
    } else {
      this.setState({queryData, listData: []})
    }
    Taro.hideLoading()
  }

  // 开始时间
  changeStart(date) {
    const queryData: any = this.state.queryData;
    queryData.search_add_date_start = date;
    // 筛选数据返回
    this.setState({
      queryData
    }, async () => {
      await this.getListData(this.state.queryData)
    });
  }

  // 结束时间
  changeEnd(date) {
    const queryData: any = this.state.queryData;
    queryData.search_add_date_end = date;
    // 筛选数据返回
    this.setState({
      queryData
    }, async () => {
      await this.getListData(this.state.queryData)
    });
  }
  async onChange(e) {
    this.page = 1
    const {supplierList, queryData} = this.state
    const supplierIndex = Number(e.detail.value)
    const supplierChecked = supplierList[supplierIndex].company
    queryData['page'] = 1
    queryData['search_supplier_id'] = supplierList[supplierIndex].supplier_id
    this.setState({supplierIndex, supplierChecked})
    Taro.setStorageSync('mySupplierIndex', supplierIndex)
    await this.getListData(queryData)
  }

  render() {
    const {listData, queryData, supplierList, supplierIndex, supplierChecked}: any = this.state;
    return (
      <View className='vedrifcation-business'>
        <GzhAuth />
        <Water />
        <View className='header-top' style={`background-color: ${process.env.mainColor}`}>
          <View className='head-picker'>
            {supplierList.length >= 1 &&
            <Picker value={supplierIndex} range={supplierList} rangeKey='company' onChange={this.onChange.bind(this)}>
              <View className={supplierChecked ? 'picker' : 'picker off'}>
                {supplierChecked ? '供应商: ' + supplierChecked : '请先选择供应商'}
                <Text>切换</Text>
              </View>
            </Picker>}
          </View>
        </View>
        <View className={`t-a-l flex h-lh while ${TARO_ENV + 'white'}`}>
          <Picker
            mode='date'
            onChange={
              ({detail: {value}}) => this.changeStart(value)
            }
            value={queryData.search_add_date_start}
            style='width: 50%;'
          >
            <View className='t-a-c w-100 p-r-0 f-24'
              style={`color:${queryData.search_add_date_start ? '#000' : '#c5c5c5'};`}
            >
              {queryData.search_add_date_start || '选择使用时间'}
            </View>
          </Picker>
          <Text style='margin: 0 20px;'>至</Text>
          <Picker
            mode='date'
            onChange={
              ({detail: {value}}) => this.changeEnd(value)
            }
            value={queryData.search_add_date_end}
            style='width: 50%;'
          >
            <View className='t-a-c w-100 p-r-0 f-24'
              style={`color:${queryData.search_add_date_end ? '#000' : '#c5c5c5'};`}
            >
              {queryData.search_add_date_end || '选择使用时间'}
            </View>
          </Picker>
        </View>
        <View className='list'>
          {
            listData.map(item => {
              return (
                <Block key={item.id}>
                  <View className='list-item'>
                    <View className='list-item-header'>
                      <View className='list-item-header-right'>
                        <View className='list-item-header-right-name'>
                          {item.supplier_name}
                        </View>
                      </View>
                    </View>
                    <View className='sale' style='margin-top: 10px;'>
                      <View className='w-30'>
                        <View className='sale-title'>
                          销售额
                        </View>
                        <View className='sale-content'>
                          <Text className='money'>￥</Text>
                          {item.total_fee}
                        </View>
                      </View>
                      <View className='w-30'>
                        <View className='sale-title'>
                          核销数量
                        </View>
                        <View className='sale-content'>
                          {item.ticket_check}
                        </View>
                      </View>
                      <View className='w-30'>
                        <View className='sale-title'>
                          销量
                        </View>
                        <View className='sale-content'>
                          {item.order_count}
                        </View>
                      </View>
                    </View>
                    <View className='sale' style='margin-top: 10px;'>
                      <View className='w-30' style='left: -10px;'>
                        <View className='sale-title'>
                          退款数量
                        </View>
                        <View className='sale-content'>
                          <Text className='money'>￥</Text>
                          {item.refund_order_count}
                        </View>
                      </View>
                      <View className='w-30' style='left: -10px;'>
                        <View className='sale-title'>
                          预付余额
                        </View>
                        <View className='sale-content'>
                          <Text className='money'>￥</Text>
                          {item.pre_money}
                        </View>
                      </View>
                      <View className='w-30' style='visibility:hidden;left: -10px;'>
                        <View className='sale-title'>
                          预付余额
                        </View>
                        <View className='sale-content'>
                          {item.percentage}
                        </View>
                      </View>
                    </View>
                  </View>
                </Block>
              )
            })
          }
        </View>
        {listData.length <= 0 && <View className='no-data'>暂无信息</View>}
        <View style='height: 30px' />
      </View>
    );
  }
}

export default Index as ComponentClass<PageOwnProps, PageState>
